<template>
  <el-card shadow="never">
    <div style="margin: 10px 0;text-align: right">
      <el-button type="primary" v-show="$permiss[1037]" @click="batchVisible = true">{{ $t('批量操作') }}</el-button>
    </div>
    <el-calendar v-model="calendarValue">
      <template
          slot="dateCell"
          slot-scope="{date, data}">
        <div class="date_cell" v-if="disableCell(data)" @click="viewStaffDate = data.day,viewStaffDetails(data)">
          {{ data.day.split('-').slice(1).join('-') }}
          <div v-if="dateCount[data.day] " style="margin-top: 5px">
            <el-button>
              {{ $t('休息人数') }} : {{ dateCount[data.day] ? dateCount[data.day] : '' }}
            </el-button>
          </div>
        </div>
        <div v-else  @click.stop="stopClick()" class="date_cell disable">
          {{ data.day.split('-').slice(1).join('-') }}
        </div>
      </template>
    </el-calendar>
    <!--    查看休息员工详情-->
    <Dialog :visible.sync="staffDetailsShow" :title="staffDetailsTitle" @close="clearDetails" :footer="false"
            width="70%">
      <el-form label-width="80px">
        <el-row :gutter="24">
          <el-col :span="19">
            <el-col :span="8" :xs="24">
              <el-form-item :label="$t('员工账号')">
                <el-input v-model="detailPage.accountNumber" clearable/>
              </el-form-item>
            </el-col>
            <el-col :span="8" :xs="24">
              <el-form-item :label="$t('员工姓名')">
                <el-input v-model="detailPage.name" clearable/>
              </el-form-item>
            </el-col>
            <el-col :span="8" :xs="24">
              <el-form-item :label="$t('角色类型')">
                <el-select v-model="detailPage.role" clearable>
                  <el-option v-for="item in selectRoleList" :label="item.name" :key="item.id"
                             :value="item.type"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-col>
          <el-col :span="5" :xs="24" style="text-align: right">
            <el-button type="primary" @click="viewStaffDetails">{{ $t('查询') }}</el-button>
            <el-button @click="resetSearchDetails">{{ $t('重置') }}</el-button>
          </el-col>
        </el-row>
      </el-form>
      <div style="text-align: right;margin-bottom: 10px">
        <el-button type="primary" @click="addRestStaff" v-show="disable() && $permiss[1038] ? true : false">{{ $t('新增') }}</el-button>
      </div>
      <Table :table-column="detailsTableColumn" :table-data="detailsTableData" :page="detailPage"
             @handleSizeChange="(val)=>{
               detailPage.pageSize = val
               viewStaffDetails()
             }"
             @handleCurrentChange="(val)=>{
               detailPage.pageNum = val
               viewStaffDetails()
             }"
      >
        <template slot="status" slot-scope="{row}">
          <el-switch @change="changeStatus(row)" :disabled="!disable() && $permiss[1036]? true : false"
                     :value="row.status === 1"></el-switch>
        </template>
      </Table>
    </Dialog>
    <!--     新增员工-->
    <Dialog :visible.sync="addRestStaffShow" width="60%" :title="$t('选择员工')" @confirm="addStaffConfirm"
            @cancel="addRestStaffShow = false">
      <el-form label-width="80px">
        <el-row :gutter="24">
          <el-col :span="19">
            <el-col :span="8" :xs="24">
              <el-form-item :label="$t('员工账号')">
                <el-input v-model="addPage.accountNumber" clearable/>
              </el-form-item>
            </el-col>
            <el-col :span="8" :xs="24">
              <el-form-item :label="$t('员工姓名')">
                <el-input v-model="addPage.adminName" clearable/>
              </el-form-item>
            </el-col>
            <el-col :span="8" :xs="24">
              <el-form-item :label="$t('角色类型')">
                <el-select v-model="addPage.type" clearable>
                  <el-option v-for="item in selectRoleList" :label="item.name" :key="item.id"
                             :value="item.type"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-col>
          <el-col :span="5" :xs="24" style="text-align: right">
            <el-button type="primary" @click="addRestStaff">{{ $t('查询') }}</el-button>
            <el-button @click="addSearchReset">{{ $t('重置') }}</el-button>
          </el-col>
        </el-row>
      </el-form>
      <Table :table-column="addTableColumn" :selection="true" :select-rows="addSelectRows" :table-data="addTableData"
             :page="addPage"
             @handleSelectionChange="(val)=>{
               addSelectRows = val
             }"
             @handleSizeChange="(val)=>{
               addPage.pageSize = val
               getPeopleStaff()
             }"
             @handleCurrentChange="(val)=>{
               addPage.pageNum = val
               getPeopleStaff()
             }"
      >
      </Table>
    </Dialog>
    <!--  选择多个日期-->
    <Dialog :visible.sync="batchVisible" :title="$t('批量操作')" @cancel="batchVisible = false"
            @confirm="batchSelectConfirm" @close="multipleDateSelect = ''">
      <el-date-picker
          style="width: 100%"
          type="dates"
          v-model="multipleDateSelect"
          :pickerOptions="pickerOptions"
          :placeholder="$t('选择一个或多个日期')">
      </el-date-picker>
    </Dialog>
  </el-card>
</template>

<script>
import dayjs from "dayjs";
import {schedulingBatchInsert,schedulingCount,fetchSchedulingList,schedulingUpdate,fetchLowerRole,selectStaff} from '@/api/system'

export default {
  data() {
    return {
      calendarValue: new Date(),
      dateCount: {},
      staffDetailsShow: false,
      viewStaffDate: null,
      detailPage: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      selectRoleList: [],
      detailsTableColumn: [
        {label: this.$t('员工帐号'), prop: 'accountNumber', align: 'center', minWidth: 150},
        {label: this.$t('姓名'), prop: 'adminName', align: 'center', minWidth: 100},
        {label: this.$t('角色'), prop: 'role', align: 'center', minWidth: 100},
        {label: this.$t('创建时间'), prop: 'creationTime', align: 'center', minWidth: 150},
        {label: this.$t('是否休息'), slot: 'status', align: 'center', minWidth: 100},
      ],
      detailsTableData: [],
      addRestStaffShow: false,
      addPage: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      addTableColumn: [
        {label: this.$t('员工帐号'), prop: 'accountNumber', align: 'center'},
        {label: this.$t('姓名'), prop: 'adminName', align: 'center'},
        {label: this.$t('角色'), prop: 'name', align: 'center'},
      ],
      addTableData: [],
      addSelectRows: [],
      batchVisible: false,
      multipleDateSelect: '',
      pickerOptions: {
        disabledDate: (time) => {
          return time.getTime() < new Date().setTime((new Date().getTime() - 24*60*60*1000)) || Object.keys(this.dateCount).map(item => dayjs(item).valueOf()).indexOf(time.getTime()) !== -1
        }
      }
    }
  },
  computed: {
    staffDetailsTitle() {
      return this.viewStaffDate + ' - ' + this.$t('休息员工详情')
    }
  },
  mounted() {
    // 上一页
    const prevBtn = document.querySelector(
        ".el-calendar__button-group .el-button-group>button:nth-child(1)"
    );
    prevBtn.addEventListener("click", () => {
      this.getSchedulingList()
    });
    // 下一页
    const nextBtn = document.querySelector(
        ".el-calendar__button-group .el-button-group>button:nth-child(3)"
    );
    nextBtn.addEventListener("click", () => {
      this.getSchedulingList()
    });
    //点击今天
    const todayBtn = document.querySelector(
        ".el-calendar__button-group .el-button-group>button:nth-child(2)"
    );
    todayBtn.addEventListener("click", () => {
      this.getSchedulingList()
    });

    this.getSchedulingList()
    this.selectRoleName()
  },
  methods: {
    // 获排班列表员工总数值
    async getSchedulingList() {
      const res = await schedulingCount({
        pageNum: 1,
        pageSize: 100,
        time: dayjs(this.calendarValue).format('YYYY-MM')
      })
      if (res.code === 1 && res.data) {
        const obj = {}
        const data = res.data
        data.forEach(item => {
          obj[item.time] = item.count
        })
        this.dateCount = obj
      }
    },
    //  查看当前日期排班详情
    async viewStaffDetails(row,e) {
      const res = await fetchSchedulingList({...this.detailPage, time: this.viewStaffDate})
      if (res.code === 1) {
        const {list, pageNum, pageSize, total} = res.data
        this.staffDetailsShow = true
        this.detailsTableData = list
        this.detailPage = {
          ...this.detailPage,
          pageNum, pageSize, total
        }
      }
    },
    resetSearchDetails() {
      this.detailPage = {
        pageNum: 1,
        pageSize: 10,
        total: 0
      }
      this.viewStaffDetails()
    },
    // 获取角色类型下拉
    async selectRoleName() {
      const res = await fetchLowerRole()
      if (res.code === 1 && res.data) {
        this.selectRoleList = res.data
      }
    },
    // 禁用日历单元格
    disableCell({type}) {
      return type === 'current-month'
    },
    stopClick(){
      return false
    },
    // 之前的日期禁止操作
    disable() {
      // 获取昨天
      return dayjs(this.calendarValue).valueOf() > new Date().setTime((new Date().getTime() - 24*60*60*1000))
    },
    // 切换状态
    async changeStatus({id, status}) {
      const res = await schedulingUpdate({
        id,
        status: status === 1 ? 0 : 1
      })
      if (res.code === 1) {
        this.$message.success(this.$t('操作成功'))
        this.viewStaffDetails()
        this.getSchedulingList()
      }
    },
    clearDetails() {
      this.detailPage = {
        pageNum: 1,
        pageSize: 10,
        total: 0
      }
    },

    // 新增员工
    async addRestStaff() {
      this.addRestStaffShow = true
      this.addType = 'single'
      await this.getPeopleStaff(this.viewStaffDate)
    },
    addSearchReset() {
      this.addPage = {
        pageNum: 1,
        pageSize: 10,
        total: 0
      }
      this.getPeopleStaff()
    },
    // 获取员工列表
    async getPeopleStaff(time) {
      const res = await selectStaff({
        ...this.addPage,
        time
      })
      if (res.code === 1) {
        const {list, pageNum, pageSize, total} = res.data
        this.addTableData = list
        this.addPage = {
          ...this.addPage,
          pageNum, pageSize, total
        }
      }
    },
    // 绑定休息员工
    async addStaffConfirm() {
      let list = []
      if (this.addType === 'single') {
        // 单选日期
        list = this.addSelectRows.map(item => {
          item.time = this.viewStaffDate
          item.systemUserId = item.adminUserId
          delete item.adminUserId
          return item
        })
      } else {
        // 多选日期
        const multipleDateSelect = this.multipleDateSelect.map(item => dayjs(item).format('YYYY-MM-DD'))
        multipleDateSelect.forEach(i => {
          this.addSelectRows.forEach(item => {
            list.push({
              ...item,
              time: i,
              systemUserId: item.adminUserId,
              adminUserId: undefined
            })
          })
        })
      }
      const res = await schedulingBatchInsert(list)
      if (res.code === 1) {
        this.$message.success(this.$t('操作成功'))
        this.addRestStaffShow = false
        if (this.addType === 'single') {
          // 单选日期
          this.viewStaffDetails()
          this.getSchedulingList()
        } else {
          // 多选日期
          this.batchVisible = false
          this.getSchedulingList()
        }
      }
    },
    async batchSelectConfirm() {
      if (this.multipleDateSelect){
        this.addRestStaffShow = true
        this.addType = 'multiple'
        await this.getPeopleStaff()
      }
    }
  }
}
</script>

<style scoped>
.date_cell {
  padding: 8px;
  box-sizing: border-box;
  height: 100%;
  text-align: center;
}

.disable {
  background-color: #f5f7fa;
  opacity: 1;
  cursor: not-allowed;
  color: #c0c4cc;
}

::v-deep .el-calendar-table .el-calendar-day {
  padding: 0 !important;
}
</style>
